<template>
  <div class="px-[20px]">
    <div class="flex items-center justify-between py-[10px]">
      <div class="flex cursor-pointer">
        <Breadcrumb>
          <BreadcrumbItem
            v-for="(item, index) in pathList"
            :key="JSON.stringify(item)"
            @click="handlePath(item, index)"
            ><span class="text-[18px]">
              {{ item.folder }}
            </span>
          </BreadcrumbItem>
        </Breadcrumb>
      </div>
      <div>
        <Button class="mr-[5px]" type="primary" @click.stop="donwloadAllFile">下载</Button>
        <Button
          type="primary"
          @click="
            () => {
              isCheck = !isCheck;
              nextTick(() => {
                setTableData(archivesList);
                setPagination({
                  total,
                  current: queryParams.current,
                  pageSize: queryParams.size,
                });
                selectionList = [];
              });
            }
          "
          >切换</Button
        >
      </div>
    </div>
    <div class="bg-white border border-[#d9d9d9] border-solid px-[20px] py-[10px] mb-[20px]">
      <Input
        class="w-[200px] mr-[20px]"
        v-model:value="queryParams.keyword"
        allowClear
        placeholder="搜索关键词"
      />
      <Button type="primary" class="mr-[10px]" @click="goBack" :disabled="pathList.length <= 1"
        >返回上一层</Button
      >
      <Button type="primary" @click="searchQuery">搜索</Button>
    </div>
    <div
      v-if="isCheck"
      class="bg-white border border-[#d9d9d9] border-solid p-[20px] pb-[60px] relative"
    >
      <div class="flex flex-wrap">
        <div
          class="flex items-start p-[15px] mr-[25px] cursor-pointer hover:bg-[#edecec] max-w-[12%]"
          v-for="item in archivesList"
          :key="item"
        >
          <Checkbox class="mr-[5px]" v-model:checked="item.checked" @change="changeFile" />
          <Tooltip>
            <template #title>
              <div>文件大小：{{ convertedFileSize(item.size) }}</div>
              <div>文件数量：{{ item.count }}</div>
              <div>文件路径：{{ item.path }}</div>
            </template>
            <div @click.stop="handleClick(item)" class="flex flex-col items-center w-[80%]">
              <img
                v-if="item.folder"
                class="w-[90px]"
                src="@/assets/images/archives/wenjianjia.png"
                alt=""
              />
              <img v-else class="w-[90px]" :src="getFileIconWithSuffix(item.name)" alt="" />
              <!-- <img v-else class="w-[90px]" src="@/assets/images/archives/pdf.png" alt="" /> -->
              <div class="my-[5px] text-[16px] text-center break-words w-[130px]">{{
                item.folder || item.name
              }}</div>
              <div class="text-[12px] text-[#959191]">{{
                getDate.formatDateToYYYYMMDD(item.updateTime)
              }}</div>
            </div>
          </Tooltip>

          <DownloadOutlined
            @click.stop="downLoadFile(item)"
            class="text-[16px] mt-[4px] ml-[5px]"
          />
        </div>
      </div>
      <Pagination
        class="absolute right-[30px] bottom-[20px]"
        :showSizeChanger="true"
        @change="onShowSizeChange"
        v-model:current="queryParams.current"
        v-model:page-size="queryParams.size"
        :total="total"
        :show-total="(total) => `共 ${total} 条数据`"
      />
    </div>
    <div v-else class="bg-white border border-[#d9d9d9] p-[20px] pb-[60px] relative">
      <BasicTable
        class="mb-[20px]"
        style="height: auto"
        @change="tableChange"
        @selection-change="selectionChange"
        @register="registerTable"
      >
        <template #bodyCell="{ column, record, text }">
          <template v-if="column.key === 'folder'">
            <div
              class="flex items-center justify-center cursor-pointer"
              @click.stop="handleClick(record)"
            >
              <img
                v-if="record.folder"
                class="w-[24px]"
                src="@/assets/images/archives/wenjianjia.png"
                alt=""
              />
              <img v-else class="w-[24px]" :src="getFileIconWithSuffix(record.name)" alt="" />
              <!-- <img v-else class="w-[24px]" src="@/assets/images/archives/pdf.png" alt="" /> -->
              <span class="ml-[5px]">{{ text || record.name }}</span>
            </div>
          </template>

          <template v-if="column.key === 'size'">
            <div class="flex items-center justify-center">
              {{ convertedFileSize(record.size) }}
            </div>
          </template>

          <template v-if="column.key === 'action'">
            <div class="flex items-center justify-center">
              <Button class="mr-[5px]" type="link" @click="downLoadFile(record)">下载</Button>
              <preview-btn v-if="!record.folder" :fileUrl="record.url" :fileName="record.name" />
            </div>
          </template>
        </template>
      </BasicTable>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted, nextTick } from 'vue';
  import {
    Button,
    Input,
    Pagination,
    Checkbox,
    Breadcrumb,
    BreadcrumbItem,
    message,
    Tooltip,
  } from 'ant-design-vue';
  import { DownloadOutlined } from '@ant-design/icons-vue';
  import { getDate } from '@/utils/time';
  import { getByMapList } from '@/api/eslogis-tps/index';
  import PreviewBtn from '@/components/common/PreviewBtn.vue';
  import { BasicTable, ColumnChangeParam, useTable } from '@/components/Table';
  import { downloadFileApi, downloadBatch } from '@/api/escloud/upload';
  import { useLoading } from '@/components/Loading';
  import { downloadFile } from '@/utils/common/index';

  import image from '@/assets/images/archives/file_img.png';
  import tif from '@/assets/images/archives/file_tif.png';
  import video from '@/assets/images/archives/file_video.png';
  import audio from '@/assets/images/archives/file_music.png';
  import excel from '@/assets/images/archives/file_excle.png';
  import word from '@/assets/images/archives/file_word.png';
  import archive from '@/assets/images/archives/file_zip.png';
  import pdf from '@/assets/images/archives/file_pdf.png';
  import ppt from '@/assets/images/archives/file_ppt.png';
  import text from '@/assets/images/archives/file_txt.png';

  const [openFullLoading, closeFullLoading] = useLoading({
    tip: '加载中...',
  });

  const isCheck = ref(true);

  const archivesList = ref([]);

  const selectionList = ref([]);

  const pathList = ref([
    {
      folder: '档案管理',
      path: '',
    },
  ]);

  const total = ref(10);

  const queryParams = ref({
    current: 1,
    size: 10,
    keyword: '',
    path: '',
    isSearchCount: true,
  });

  onMounted(async () => {
    await initQuery();
  });

  function getFileTypeWithExt(ext) {
    if (ext) {
      ext = ext.toLowerCase();
      if (['jpg', 'png', 'jpeg', 'bmp', 'ico', 'gif'].includes(ext)) {
        return 'image';
      } else if (ext === 'psd') {
        return 'psd';
      } else if (ext === 'tif') {
        return 'tif';
      } else if (['mp4', 'm2v', 'mkv', 'rmvb', 'wmv', 'avi', 'flv', 'mov', '3gp'].includes(ext)) {
        return 'video';
      } else if (['mp3', 'wma', 'wav'].includes(ext)) {
        return 'audio';
      } else if (['xlsx', 'xls'].includes(ext)) {
        return 'excel';
      } else if (['doc', 'docx'].includes(ext)) {
        return 'word';
      } else if (['rar', 'zip', '7z', 'tar', 'iso', 'dmg'].includes(ext)) {
        return 'archive';
      } else if (ext === 'pdf') {
        return 'pdf';
      } else if (['ppt', 'pptx'].includes(ext)) {
        return 'ppt';
      } else if (['txt', 'text'].includes(ext)) {
        return 'text';
      }
    }
    return 'pdf';
  }

  function getFileIconWithSuffix(fileName) {
    const index = fileName.lastIndexOf('.');
    const ext = fileName.substr(index + 1) || '';
    const fileType = getFileTypeWithExt(ext);
    if (fileType) {
      return {
        image,
        tif,
        video,
        audio,
        excel,
        word,
        archive,
        pdf,
        ppt,
        text,
      }[fileType];
    }
  }

  const tableChange = async ({ current, pageSize }) => {
    try {
      queryParams.value.current = current;
      queryParams.value.size = pageSize;
      await initQuery();
    } catch (error) {
      console.log('🚀 ~ onShowSizeChange ~ error:', error);
    }
  };

  const initParams = () => {
    queryParams.value = {
      current: 1,
      size: 10,
      keyword: '',
      path: '',
      isSearchCount: true,
    };
  };

  const onShowSizeChange = async (current: number, pageSize: number) => {
    console.log('🚀 ~ onShowSizeChange ~ current:', current);
    try {
      queryParams.value.current = current;
      queryParams.value.size = pageSize;
      await initQuery();
    } catch (error) {
      console.log('🚀 ~ onShowSizeChange ~ error:', error);
    }
  };

  const searchQuery = async () => {
    try {
      queryParams.value = {
        ...queryParams.value,
        current: 1,
        size: 10,
        isSearchCount: true,
      };
      initQuery();
    } catch (error) {
      console.log('🚀 ~ searchQuery ~ error:', error);
    }
  };

  const initQuery = async () => {
    try {
      openFullLoading();
      const res = await getByMapList(queryParams.value);
      archivesList.value = res.records;
      total.value = res.total;

      if (!isCheck.value) {
        setTableData(archivesList.value);
        setPagination({
          total: res.total,
          current: queryParams.value.current,
          pageSize: queryParams.value.size,
        });
      }

      closeFullLoading();

      // 清空多选
      selectionList.value = [];
    } catch (error) {
      console.log('🚀 ~ initQuery ~ error:', error);
      closeFullLoading();
    }
  };

  const goBack = async () => {
    const index = pathList.value.length - 2;
    handlePath(pathList.value[index], index);
  };

  // 文件大小转化
  const convertedFileSize = (size: number) => {
    const units = ['B', 'KB', 'MB', 'GB'];
    let index = 0;

    while (size >= 1024 && index < units.length - 1) {
      size /= 1024;
      index++;
    }

    // 保留两位小数
    return [0, 1].includes(index)
      ? `${size.toFixed(0)} ${units[index]}`
      : `${size.toFixed(2)} ${units[index]}`;
  };

  // const isImageFile = (filename) => {
  //   // 定义图片后缀的数组
  //   const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];

  //   // 获取文件名中的后缀部分
  //   const extension = filename.split('.').pop().toLowerCase();

  //   // 检查后缀是否在图片后缀数组中
  //   return imageExtensions.includes(extension);
  // };

  const [registerTable, { setTableData, setPagination }] = useTable({
    canResize: true,
    pagination: true,
    bordered: true,
    columns: [
      {
        title: '文件',
        dataIndex: 'folder',
      },
      {
        title: '上传时间',
        dataIndex: 'updateTime',
      },
      {
        title: '文件大小',
        dataIndex: 'size',
      },
      {
        title: '交货计划号',
        dataIndex: 'deliveryCode',
      },
      {
        title: '销售订单号',
        dataIndex: 'orderSn',
      },
      {
        title: '操作',
        dataIndex: 'action',
      },
    ],
    rowSelection: {
      type: 'checkbox',
    },
    onColumnsChange: (data: ColumnChangeParam[]) => {
      console.log('ColumnsChanged', data);
    },
  });

  function selectionChange({ rows }) {
    selectionList.value = rows.map((item) => {
      if (item.folder) {
        return {
          path: item.path,
        };
      } else {
        return {
          name: item.name,
          url: item.url,
        };
      }
    });
  }

  const changeFile = () => {
    selectionList.value = archivesList.value
      .map((item: any) => {
        if (item.checked) {
          return {
            name: item.name,
            url: item.url,
            path: item.path,
            folder: item.folder,
          };
        }
      })
      .filter((e) => {
        return e;
      }) as any;
  };

  const handlePath = async (item, index) => {
    initParams();
    queryParams.value.path = item.path;
    await initQuery();
    pathList.value.splice(index + 1);
  };

  const handleClick = async (item) => {
    // folder代表文件夹，否则为普通文件
    if (item.folder) {
      pathList.value.push({
        folder: item.folder,
        path: item.path,
      });
      initParams();
      queryParams.value.path = item.path;
      await initQuery();
    } else {
      window.open(item.url, '_blank');
    }
  };

  const download = (data, filename?) => {
    downloadFile(data, filename ? filename : '合并文件.zip');
  };

  // 下载文件
  const downLoadFile = async (item) => {
    try {
      openFullLoading();
      if (item.folder) {
        const data = (await downloadBatch([item])) as any;
        if (data) {
          download(data, item.folder + '.zip');
        } else {
          message.error('下载失败');
        }
      } else {
        const data = (await downloadFileApi(item.url)) as any;
        if (data) {
          download(data, item.name);
          // const blobUrl = window.URL.createObjectURL(data);
          // // 这里的文件名根据实际情况从响应头或者url里获取
          // const a = document.createElement('a');
          // a.href = blobUrl;
          // a.download = item.name;
          // a.click();
          // window.URL.revokeObjectURL(blobUrl);
        } else {
          message.error('下载失败');
        }
      }
      closeFullLoading();
    } catch (error) {
      // message.error(error || '系统错误');
      closeFullLoading();
    }
  };

  const donwloadAllFile = async () => {
    if (selectionList.value.length <= 0) {
      message.error('请选择要下载的文件');
      return;
    }
    try {
      openFullLoading();
      const data = (await downloadBatch(selectionList.value)) as any;
      if (data) {
        download(data);
      } else {
        message.error('下载失败');
      }
      closeFullLoading();
    } catch (error) {
      // message.error(error || '系统错误');
      closeFullLoading();
    }
  };
</script>
